var app = require('express')()
var server = require('http').Server(app);
var port = parseInt(process.argv[2] || '3100');
server.listen(port)

var io = require('socket.io')(server)
var srdis = require('socket.io-redis')

var config = require('../configs/config')

// 设置socket集群，采用redis进行共享
io.adapter(srdis({host: config.redis.host, port: config.redis.port}))

// 加载服务
var services = []
config.services.forEach(function(srv) {
    services.push(require(srv))
})

var SocketIOStart = function() {
    io.on('connection', function(so) {
        console.log(so.id + ' connected')
        so.emit('connected', {data: 'hello, you connected'})

        // 定点全局推送，由外部cront创建socket发送消息到服务端，服务端进行客户端广播
        so.on('push', function(data) {
            console.log(data)
            io.emit('push_global', {data: data})
        })

        // 加载业务服务
        services.forEach(function(srv) {
            srv(so, io)
        })
    })

}

module.exports = SocketIOStart
